package com.sams.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.sams.entity.School;
import com.sams.entity.User;
import com.sams.service.SchoolService;
import com.sams.util.POIUtil;

@RequestMapping("/school")
@Controller
public class SchoolController {

	@Autowired
	private SchoolService service;
	 
	@RequestMapping("/list")
	public String listSchool(Integer currentPage,String names ,Model model) {
		if(currentPage==null) {
			currentPage=1;
		}
		// 以前存 list  和  page对象 ，现在存 分页框架的pageInfo
		// PageInfo 相当于  以前的Page 
		 
		PageInfo<School> pageInfo = service.listSchool(currentPage,names);
		model.addAttribute("pageInfo", pageInfo);
		model.addAttribute("names", names);
		 
		return "school";
	}
	
	@RequestMapping("/findById")
	public School findById(Integer id) {
		return  service.findById(id);
	}
	
	@RequestMapping("/delete")
	public String delete(Integer id) {
		service.delete(id);

		return "forward:/school/list";
	}
	
	@RequestMapping("/add")
	public String add(School sc,Model model) throws IOException {
		 boolean flag = service.validate(sc.getName(), sc.getLevel());
		 
		if(!flag) {
		//	response.setContentType("text/html;charset=UTF-8");
		//	PrintWriter out = response.getWriter();
		//	out.print("<script>alert('当前学校已存在启用状态的记录，不能再次启用！');location.href='list';</script>");
		     model.addAttribute("error", "当前学校已存在启用状态的记录，不能再次启用");
			return "error";
		} 
		
		sc.setStatus(1);
		try {
			service.add(sc);
		} catch (Exception e) {
			   model.addAttribute("error", e.getMessage());
				return "error";
		}
		return "forward:/school/list";
	}
 
	@RequestMapping("/update")
	public String update(School stu) {
		service.update(stu);
		return "forward:/school/list";
	}
	
	@RequestMapping("/updateStatus")
	public String updateStatus(Integer id,Integer status,String name,String level,HttpServletResponse response) throws IOException {
		if(status==1) {
			//要启用，首先需要验证 name是否存在已启用的
			 boolean flag = service.validate(name, level);
			if(!flag) {
				response.setContentType("text/html;charset=UTF-8");
				PrintWriter out = response.getWriter();
				out.print("<script>alert('当前学校已存在启用状态的记录，不能再次启用！');location.href='list';</script>");
				return "";
			} 
		}
		
		service.updateStatus(id,status);

		return "forward:/school/list";
	}
	
	@RequestMapping("/downTemplate")
	public String downTemplate(HttpServletRequest request, HttpServletResponse response) {
		 // 1: 找到excel文件
        String storePath = request.getSession().getServletContext().getRealPath("/") + "template/school/";
        String fileName = "学校批量导入.xlsx";

        File file = new File(storePath + fileName);
        if (!file.exists()) {
            throw new RuntimeException("file do not exist");
        }
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        // 重置response
        response.reset();
        //设置http头信息的内容
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
        int fileLength = (int) file.length();
        response.setContentLength(fileLength);

        try {
            if (fileLength != 0) {
                inputStream = new FileInputStream(file);
                byte[] buf = new byte[4096];
                // 创建输出流
                servletOutputStream = response.getOutputStream();
                int readLength;
                // 读取文件内容并输出到response的输出流中
                while ((readLength = inputStream.read(buf)) != -1) {
                    servletOutputStream.write(buf, 0, readLength);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("download file error");
        } finally {
            try {
                // 关闭ServletOutputStream
                if (servletOutputStream != null) {
                    servletOutputStream.flush();
                    servletOutputStream.close();
                }
                // 关闭InputStream
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
 
	}
	/**
	 * excel批量导入
	 * @return
	 */
	@RequestMapping("/importBetch")
	public String ExcelInport(@RequestParam("file") MultipartFile file,HttpServletRequest request,Model model) {
		// 1.获取前端表单上传的文件，获取文件名getOriginalFilename()，判断是否是Excel文件
		String fileName = file.getOriginalFilename();
		System.out.println(fileName);
		// * 2.1不是Excel文件，直接返回提示信息
		if (!(fileName.contains("xls") || fileName.contains("xlsx"))) {
			// 格式错误
			model.addAttribute("error", "上传的文件格式不对");
			return "error";
		}
 
		// * 2.2是Excel文件，由于浏览器不能显示文件的绝对路径，所以将文件上传保存在本地的另一个位置
		// * 3.创建上传目录 realpath="D:/uploadExcel"（如果目录不存在）
		String realpath = request.getSession().getServletContext().getRealPath("/");
		System.out.println(realpath);
		// * 2.2是Excel文件，由于浏览器不能显示文件的绝对路径，所以将文件上传保存在本地的另一个位置
		// * 3.创建上传目录 realpath="D:/uploadExcel"（如果目录不存在）
		//String realpath = "D:/uploadExcel";
		File targetDir = new File(realpath+"/uploadExcel");
		if (!targetDir.exists()) {
			targetDir.mkdirs();
			System.out.println("不存在目录");
		}
		// * 4.将上传文件保存在上传目录中new File(realpath,fileName)
		File targetFile = new File(realpath+"/uploadExcel", fileName);
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			// 导入错误
			model.addAttribute("error", "文件上传失败");
			 return "error";
		}
		
		User user =  (User)request.getSession().getAttribute("user");
		if(user==null) {
			model.addAttribute("error", "会话过期，请重新登录");
			return "error";
		}
		// // 2: 解析excel数据
        List<String[]> excelData;
		try {
			excelData = POIUtil.readExcel(file);
		} catch (IOException e1) {
			model.addAttribute("error", e1.getMessage());
		     return "error";
		}

        List<School> schoolList = new ArrayList<School>();
        for(String[] arr : excelData) {
        	School sc = new School();
        	sc.setName(arr[0].trim());
        	sc.setCode(arr[1].trim());
        	sc.setProp(arr[2].trim());
        	sc.setLevel(arr[3].trim());
        	sc.setStudyyear(arr[4].trim());
        	sc.setTerm(arr[5].trim());
        	sc.setStatus(1);
        	sc.setUserid(user.getId());
        	schoolList.add(sc);
        }
         
        //批量插入
        try {
        	boolean flag  = service.insertBatch(schoolList);
        	//成功
        	return "forward:/school/list";
        }catch (Exception e) {
        	model.addAttribute("error", e.getMessage());
		     return "error";
		}
	}
	
	public static void main(String[] args) {
		Long a = new Long("3142000312".trim());
		System.out.println(a);
	}
	
	
	/**
	 * 根据选择的乡镇id 查询它下面的所属学校
	 * @param zid
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getSchoolByZid")
	public List<School> selectSchoolByZid(Integer zid) {
		// TODO Auto-generated method stub
		return service.selectSchoolByZid(zid);
	}
}
